package com.forester.foresterplatform.system.config;

import io.swagger.models.auth.In;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.List;

@Configuration
@EnableSwagger2WebMvc  // 开启swagger 2
public class Knief4jConfig {

    @Bean(value = "dockerBean")
    public Docket dockerBean() {
        // 指定swagger2规范
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        // 描述字段支持Markdown语法
                        .description("# Knife4j RESTful APIs")
                        .termsOfServiceUrl("http://www.forester.cn/")
                        .contact(new Contact("forester", "www.forester.cn", "geek_zh@163.com"))
                        .version("1.0")
                        .build())
                // 分组名称
                .groupName("用户服务")
                .select()
                // 这里指定Controller扫描包的路径
                .apis(RequestHandlerSelectors.basePackage("com.forester.foresterplatform.system.controller"))
                // 也可以扫描带有 ApiOptions 注解的类, 如果同时指定两个 apis, 则是 and 关系, 必须同时满足
                // .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                // 安全方案 : knife4j 具有直接调用接口的功能, 因此需要配置安全认证相关的内容
                .securitySchemes(securitySchemes())
                // 安全上下文
                .securityContexts(securityContexts());
    }

    /**
     * 安全方案
     * @return
     */
    private List<? extends SecurityScheme> securitySchemes() {
        // 安全模式, 这里指定 token 通过 Authorization 请求头传递, 即请求时需要携带 Authorization 请求头
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", In.HEADER.toValue());
        return List.of(apiKey);
    }

    private List<SecurityContext> securityContexts() {
        return List.of(SecurityContext.builder()
                .securityReferences(List.of(
                        new SecurityReference("Authorization", new AuthorizationScope[]{
                                new AuthorizationScope("global", "")})))
                .forPaths(PathSelectors.regex("^(?!auth).*$"))
                .build()
        );
    }
}
